import React, { useEffect, useState } from 'react';
import { Tree } from 'antd';
import type { TreeDataNode, TreeProps } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { CURRENT_NODE_TYPE, iconMap } from '../../../consts';
import styles from './index.module.less'
import { useNavigate, useParams } from 'react-router-dom';
import findPathByKey from './getExpandedKeys';
import { CustomIcon } from '../../../components';


const MenuTree = () => {
    const { key }: any = useParams()

    const [gData, setGData] = useState<any>([]);
    const [currentNode, setCurrentNode] = useState<CURRENT_NODE_TYPE>();
    const [expandedKeys, setExpandedKeys] = useState<number[]>([])
    const navigate = useNavigate();
    useEffect(() => {
        // navigate(`/myfile`)
    }, [])
    useEffect(() => {
        const arr: any = findPathByKey(gData, key)
        // arr?.splice(arr.length - 1, 1)
        setExpandedKeys([...Array.from(new Set([...arr || [], ...expandedKeys]))]);
    }, [key])
    const onDrop: TreeProps['onDrop'] = (info) => {
        // console.log(info);
        const dropKey = info.node.key;
        const dragKey = info.dragNode.key;
        const dropPos = info.node.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]); // the drop position relative to the drop node, inside 0, top -1, bottom 1

        const loop = (
            data: TreeDataNode[],
            key: React.Key,
            callback: (node: TreeDataNode, i: number, data: TreeDataNode[]) => void,
        ) => {
            for (let i = 0; i < data.length; i++) {
                if (data[i].key === key) {
                    return callback(data[i], i, data);
                }
                if (data[i].children) {
                    loop(data[i].children!, key, callback);
                }
            }
        };
        const data = [...gData];

        // Find dragObject
        let dragObj: TreeDataNode;
        loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1);
            dragObj = item;
        });

        if (!info.dropToGap) {
            // Drop on the content
            loop(data, dropKey, (item) => {
                item.children = item.children || [];
                // where to insert. New item was inserted to the start of the array in this example, but can be anywhere
                item.children.unshift(dragObj);
            });
        } else {
            let ar: TreeDataNode[] = [];
            let i: number;
            loop(data, dropKey, (_item, index, arr) => {
                ar = arr;
                i = index;
            });
            if (dropPosition === -1) {
                // Drop on the top of the drop node
                ar.splice(i!, 0, dragObj!);
            } else {
                // Drop on the bottom of the drop node
                ar.splice(i! + 1, 0, dragObj!);
            }
        }
        setGData(data);
        const newNode = findNode(data)
        newNode && navigate(`/myfile/${newNode.dropType}/${newNode.key}`,
            { replace: true, state: { node: JSON.parse(JSON.stringify(newNode)) } })
    };
    const handleAllowDrop = ({ dropNode }: any) => {
        const { dropType } = dropNode;
        switch (dropType) {
            case 'folder':
                return true;
            case 'md':
            case 'excel':
                return false;
            default:
                return true
        }
    };

    const createTreeData = () => {
        const defaultData: any = [
            {
                title: 'parent 1',
                key: 1,
                dropType: 'folder',
                folderDescribe: '这是一个测试数据、用来测试描述的',
                children: [
                    {
                        title: 'parent 1-0',
                        key: 2,
                        dropType: 'folder',
                        folderDescribe: '这是一个测试数据、用来测试描述的',
                        children: [
                            {
                                title: 'lsdfsdfsfdsdfsdfeaf',
                                key: 3,
                                disableCheckbox: true,
                                dropType: 'md'
                            },
                            {
                                title: 'leaf',
                                key: 4,
                                dropType: 'md'
                            },
                        ],
                    },
                    {
                        title: 'leaf',
                        key: 9,
                        disableCheckbox: true,
                        dropType: 'md'
                    },
                ],
            }, {
                title: 'parentaasdfsdfa 1-1',
                folderDescribe: '这是一个测试数据、用来测试描述的',
                key: 8,
                dropType: 'folder',
                children: [{ title: 'ss111s', key: 10086, dropType: 'md' }],
            },
            {
                title: '这个里面有表格',
                folderDescribe: '这是一个测试数据、用来测试描述的',
                key: 10,
                dropType: 'folder',
                children: [{ title: '统计表格', key: 11, dropType: 'excel' }],
            },
            {
                title: '流程图',
                folderDescribe: '这是一个测试数据、用来测试描述的',
                key: 12,
                dropType: 'folder',
                children: [{ title: 'ss111s', key: 13, dropType: 'drawingBoard' }],
            },
        ]
        // const processedData = addDataIcon(defaultData, iconMap)
        setGData(defaultData)
    }
    useEffect(() => {
        createTreeData()
    }, [])
    const findNode = (data: any[]): any | undefined => {
        for (const item of data) {
            if (item.key === currentNode?.key) {
                return item;
            }

            if (item.children) {
                const foundInChildren = findNode(item.children);
                if (foundInChildren !== undefined) {
                    return foundInChildren;
                }
            }
        }

        return undefined; // 如果未找到匹配的节点，返回 undefined
    }

    const onExpand: TreeProps['onExpand'] = (expandedKeysValue: any) => {
        setExpandedKeys(expandedKeysValue);
    };
    const treeItemClick = (node: CURRENT_NODE_TYPE) => {
        setCurrentNode(node);
        navigate(`/myfile/${node.dropType}/${node.key}`,
            { state: { node: JSON.parse(JSON.stringify(node)) } })
    }
    return (
        <Tree
            className={styles.draggableTree}
            draggable={{
                icon: false
            }}
            showIcon
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            allowDrop={handleAllowDrop}
            switcherIcon={<DownOutlined />}
            blockNode
            onDrop={onDrop}
            treeData={gData}
            selectedKeys={[Number(key)]}
            titleRender={(item: CURRENT_NODE_TYPE) => item.dropType === 'folder' ?
                <div className={styles.treeItemStyle}>
                    <div onDoubleClick={() => {
                        setExpandedKeys(Array.from(new Set([...expandedKeys,Number(item.key)])))
                    }}
                        onClick={() => treeItemClick(item)} className={styles.title}>
                        <CustomIcon style={{ fontSize: 18, marginRight: 8 }} str={iconMap[item.dropType]} />
                        <span>{item.title}</span>
                    </div>
                    <div onClick={() => { console.log(item.key) }} className={styles.iconStyle}><CustomIcon str={'add-large-line'} /></div>
                </div> :
                <div className={styles.fileItemStyle} onClick={() => treeItemClick(item)}>
                    <CustomIcon style={{ fontSize: 18, marginRight: 8 }} str={iconMap[item.dropType]} />
                    <span>{item.title}</span>
                </div>}
        />
    );
};

export default MenuTree;